package codeMaker;

import java.awt.Toolkit;
import java.io.File;

import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

import constant.Constant;
import util.HttpDownloadUtil;
import util.ZipUtils;

public class UtilDownLoad {

	private JFrame frame;

	public static volatile boolean downFlag;

	/**
	 * Launch the application.
	 */
	public static void main(String url, String downLoadDir, String consoleLine) {

		UtilDownLoad window = new UtilDownLoad(url, downLoadDir, consoleLine);
		window.frame.setVisible(true);

		new Thread(() -> {
			try {

				String fileFullName = url.substring(url.lastIndexOf("/") + 1);
				File file = new File(downLoadDir + fileFullName);
				if (!file.exists()) {
					HttpDownloadUtil.downloadFile(url, downLoadDir);
					if (consoleLine != null) {
						ZipUtils.unZip(new File(downLoadDir + fileFullName), downLoadDir, Constant.zipPwd);
					}
				}

				if (consoleLine == null) {
					//更新下载标记为true
					downFlag = true;
					window.frame.dispose();
					return;
				}
				Process process = Runtime.getRuntime().exec(consoleLine);
				// 运行实用工具
				window.frame.dispose();
				process.waitFor();
			} catch (Exception e) {
				ZipUtils.delDir(new File(downLoadDir));
				JOptionPane.showMessageDialog(window.frame, "拉取失败，请检查您的网络，如网络没有问题，请联系作者", "错误",
						JOptionPane.ERROR_MESSAGE);
				throw new RuntimeException(e.getMessage());
			}

		}).start();

	}

	/**
	 * Create the application.
	 */
	public UtilDownLoad(String url, String downLoadDir, String consoleLine) {
		initialize(url, downLoadDir, consoleLine);
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize(String url, String downLoadDir, String consoleLine) {
		frame = new JFrame();
		frame.setIconImage(Toolkit.getDefaultToolkit()
				.getImage(UtilDownLoad.class.getResource("/javax/swing/plaf/metal/icons/ocean/hardDrive.gif")));
		frame.setResizable(false);
		frame.setBounds(100, 100, 528, 162);
		frame.setLocationRelativeTo(null);
		frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

		JLabel lblNewLabel = new JLabel("正在拉取，请耐心等待。。。");
		GroupLayout groupLayout = new GroupLayout(frame.getContentPane());
		groupLayout.setHorizontalGroup(groupLayout.createParallelGroup(Alignment.LEADING).addGroup(Alignment.TRAILING,
				groupLayout.createSequentialGroup().addContainerGap(72, Short.MAX_VALUE)
						.addComponent(lblNewLabel, GroupLayout.PREFERRED_SIZE, 405, GroupLayout.PREFERRED_SIZE)
						.addGap(45)));
		groupLayout.setVerticalGroup(groupLayout.createParallelGroup(Alignment.LEADING).addGroup(groupLayout
				.createSequentialGroup().addGap(38).addComponent(lblNewLabel).addContainerGap(71, Short.MAX_VALUE)));
		frame.getContentPane().setLayout(groupLayout);

	}
}
